#include "clientcommandsendcodec.h"
#include "../clientconmanager.h"
#include "../clientserver.h"
#include "../../common/comiocontroller.h"
#include <QVector>
#include <QByteArray>
#include <QFile>
#include <QFileInfo>
#include <QByteArray>
ClientCommandSendCodec::ClientCommandSendCodec(QObject *parent) :
    QObject(parent)
{
}

//TODO unfinish version 'SendCodec <codec> <[Windows][Linux]>' last parameter not supported.
bool ClientCommandSendCodec::execute(QStringList args)
{
    QString cstrFilepath = args.at(1);
    QFile cfileCodec(cstrFilepath);
    //if not exsit
    if(cfileCodec.exists() == false) {
        ComIOController::getInstance()->msgOutput("<ClientCommandSendCodec>:Codec file not found.", MSG_ERROR);
        return false;
    }
    //open file
    if( cfileCodec.open(QIODevice::ReadOnly) == false ) {
        ComIOController::getInstance()->msgOutput("<ClientCommandSendCodec>:Codec file open failure.", MSG_ERROR);
        return false;
    }


    QVector<ClientServer*>* acServers = &(ClientConManager::getInstance()->m_aServers);
    //send codec every server
    for(int i = 0; i < acServers->size(); i++) {
        QByteArray abMsg = "SendCodec "+QByteArray::number(cfileCodec.size())+" "+QFileInfo(cfileCodec).fileName().toAscii()+"\n";
        acServers->at(i)->m_server.write(abMsg);
        //sending codec
        qint64 llCodecSize = cfileCodec.size();
        qint64 llTotalSent = 0;
        while(cfileCodec.atEnd() == false) {
            QByteArray abRead = cfileCodec.read(64*1024);
            qint64 llWrote = acServers->at(i)->m_server.write(abRead);
            llTotalSent += llWrote;
            ComIOController::getInstance()->msgOutput(QString("<ClientCommandSendCodec>:Sending.. %1").arg(llTotalSent*100.0/llCodecSize), MSG_INFO);
            if(llWrote != abRead.size()) {
                ComIOController::getInstance()->msgOutput("<ClientCommandSendCodec>:Socket write failure.", MSG_ERROR);
                goto end;
            }
        }
    }

end:
    //close file
    cfileCodec.close();
    return true;
}
